import { defineStore } from "pinia";
import { wxLogin } from "@/common/util/wx.js";
import { postLogin, getUserInfo } from '@/common/http/module/user.js'
import { getMySociety } from "@/common/http/module/society";

export const useUserStore = defineStore("user", {
  state: () => ({
    token: uni.getStorageSync("token") || "",
    userInfo: uni.getStorageSync("userInfo") || "",
    societyList: [],
    currentSociety: '',
    parentId: '', //
  }),
  actions: {
    init() {
      this.loadUserInfo();
    },
    async login(mobile_code) {
      const { code } = await wxLogin();
      const params = { 
        parent_id: this.parentId,
        mobile_code, 
        code 
      };
      console.log('>>>>>>>> login', params);
      const loginRes = await postLogin(params);
      this.token = loginRes.data.token;
      uni.setStorageSync("token", this.token);
      await this.loadUserInfo();
      return this.userInfo;
    },
    async loadUserInfo() {
      if (!this.isLogin) return
      const userRes = await getUserInfo()
      this.userInfo = userRes.data
      uni.setStorageSync('userInfo', this.userInfo)

      this.loadClubInfo()
    },
    async loadClubInfo() {
      const { data } = await getMySociety()
      this.societyList = data
      if (!data || data.length == 0) return
      const savedSocietyId = uni.getStorageSync('society_id')
      this.currentSociety = data.find(item => item.club_id == savedSocietyId) || data[0]
      uni.setStorageSync('society_id', this.currentSociety?.club_id)
    },
    changeSociety(val) {
      this.currentSociety = val
      uni.setStorageSync('society_id', this.currentSociety?.club_id)
    },
    setParentId(val) {
      console.log('>>>>>>>> setParentId', val);
      this.parentId = val
    },
    logout() {
      this.clear();
    },
    clear() {
      uni.clearStorageSync()
      const parentId = this.parentId
      this.$reset()
      this.parentId = parentId
    },
  },
  getters: {
    isLogin: state => state.token ? true: false,
    isVip: state => state.userInfo && state.userInfo.vip_level > 0,
    isConsultant: state => state.userInfo && state.userInfo.identity == 1,
    // 是否是社长或管理员
    isSocietyManager: state => state.currentSociety?.member_position == 2,
    isSocietyCreator: state => state.currentSociety?.member_position == 3,   
    currentSocietyId: state => state.currentSociety?.club_id
  }
});
